/**
 * Generate proxy 配置各种代理域名
 * See：https://github.com/http-party/node-http-proxy#options
 */

import type { ProxyOptions } from 'vite'

type ProxyTargetList = Record<string, ProxyOptions> | undefined

const httpsRE = /^https:\/\//

export function createProxy(viteEnv: any): ProxyTargetList {
  const { VITE_PROXY_HOST } = viteEnv
  if (!VITE_PROXY_HOST) {
    console.warn('proxy error: VITE_PROXY_HOST is undefined in .env.development')
    return
  }

  /**
   * 代理的域名，参数格式如下
   * [
   *  要代理的地址,
   *  代理的域名,
   *  代理过程替换的路径（可填，默认空，主要是给代理到后端本地IP时设置的特殊路径
   * ]
   */
  const proxyList = [
    ['/test', VITE_PROXY_HOST],
  ]
  const ret: ProxyTargetList = {}

  for (const [prefix, target, rewritePrefix = ''] of proxyList) {
    const isHttps = httpsRE.test(target)
    ;
    ret[prefix] = {
      target,
      changeOrigin: true,
      ws: true,
      rewrite: (path) => path.replace(new RegExp('^' + prefix), rewritePrefix),
      ...(isHttps ? { secure: false } : {})
    }
  }
  return ret
}
